<script setup lang="ts">
import { h, onMounted, ref } from 'vue';
import type { DrawerPlacement, FormInst, FormRules, UploadFileInfo } from 'naive-ui';
import { NButton, useDialog, useMessage } from 'naive-ui';
import { CreateOutline, Search, TrashBinOutline } from '@vicons/ionicons5';
import {
  checkFolderName,
  deleteFileInfo,
  getLabelList,
  msgCheckAction,
  updateFolderInfo,
  uploadImageFile
} from '@/service/api';
import { localStg } from '@/utils/storage';

const message = useMessage();

const formRef = ref<HTMLElement & FormInst>();

// 校验规则
const rules: FormRules = {
  fileCname: {
    required: true,
    message: '请输入图片名称',
    trigger: 'blur'
  },
  fileLabel: {
    required: true,
    message: '请选择素材类型',
    trigger: 'change'
  }
};

const nameForm = ref({
  fileCname: '',
  fileLabel: undefined,
  id: undefined,
  startTime: undefined || '',
  endTime: undefined || ''
});

const active = ref(false);

const placement = ref<DrawerPlacement>('right');

const activate = (place: DrawerPlacement) => {
  active.value = true;
  placement.value = place;
  uploadFileType.value = '1';
  dateExpired.value = undefined;
};

const emit = defineEmits(['refresh']);

const props = defineProps({
  fileData: {
    type: Array,
    default: () => []
  },
  thirdParentId: {
    type: Number,
    default: 0
  }
});

const searchParams = ref({
  fileCname: '',
  fileLabel: undefined
});

const { VITE_OTHER_SERVICE_BASE_URL } = import.meta.env;

const otherUrl: any = JSON.parse(VITE_OTHER_SERVICE_BASE_URL);

const imgUrl = otherUrl.imgUrl;

const dataLoading = ref(false);

const fileList = ref([]);

const showModal = ref(false);

// 上传文件变更
const handleChange = async (data: { file: UploadFileInfo; fileList: UploadFileInfo[] }) => {
  fileList.value = data.fileList;
};

// 提交
async function uploadFile(nameType?: any) {
  const formData = new FormData();
  fileList.value?.forEach((item: any, idx) => {
    if (item.status == 'pending') {
      formData.append('files', item.file as Blob);
    }
  });
  formData.append('folderId', props.thirdParentId as any);
  if (uploadFileType.value) formData.append('fileLabel', uploadFileType.value as any);
  if (nameType) formData.append('nameType', nameType);
  if (dateExpired.value) {
    formData.append('startTime', dateExpired.value[0]);
    formData.append('endTime', dateExpired.value[1]);
  }
  dataLoading.value = true;
  const { data, error } = await uploadImageFile(formData);
  if (!error) {
    emit('refresh', props.thirdParentId, searchParams);
    dataLoading.value = false;
    active.value = false;
  }
}
// 确定点击事件
async function handleClick() {
  if (fileList.value.length == 0) {
    message.warning('请添加上传文件');
    return;
  }
  if (!uploadFileType.value) {
    message.warning('请选择素材类型');
    return;
  }
  // 校验名称
  const obj = {
    folderId: props.thirdParentId,
    fileType: uploadFileType.value,
    fileNames: fileList.value?.map(item => {
      return item.name;
    })
  };
  const { data, error } = await checkFolderName(obj);
  if (!error) {
    if (data) {
      dialog.warning({
        title: '检测到有重复图片名称',
        content: () => {
          return h(
            'div',
            {
              class: 'flex flex-col justify-center items-center text-18px'
            },
            [h('span', data), h('p', { style: 'color:#736BB1; font-size:16px' }, '请选择系统自动排序命名或覆盖')]
          );
        },
        positiveText: '覆盖',
        negativeText: '自动命名',
        onPositiveClick: () => {
          uploadFile(1);
        },
        onNegativeClick: () => {
          uploadFile(2);
        },
        negativeButtonProps: { type: 'primary', secondary: true },
        positiveButtonProps: { type: 'primary', secondary: true },
        titleStyle: { fontSize: '22px' }
      });
    } else {
      uploadFile();
    }
  }
}

function closeDrawer() {
  fileList.value = [];
}

// 搜索 切换标签条件
function handleSearch() {
  emit('refresh', props.thirdParentId, searchParams);
}

const btnValue = ref('0');

const tabs = ref();

// 获取图片标签信息
async function getLabelAllList() {
  const { data, error } = await getLabelList();

  if (!error) {
    tabs.value = data;
  }
}

function handleChangeBtn(val: any) {
  btnValue.value = val;
  if (btnValue.value != '0') {
    searchParams.value.fileLabel = Number(btnValue.value);
  } else {
    searchParams.value.fileLabel = undefined;
  }
  handleSearch();
}

function handleChangeName(item: any) {
  showModal.value = true;
  nameForm.value.fileCname = item.fileCname;
  nameForm.value.id = item.id;
  nameForm.value.fileLabel = item.fileLabel;
  nameForm.value.startTime = item.startTime;
  nameForm.value.endTime = item.endTime;
  if (item.startTime && item.endTime) {
    dateFormatted.value = [String(nameForm.value.startTime), String(nameForm.value.endTime)];
  } else {
    dateFormatted.value = null;
  }
}

const dialog = useDialog();

function handleDeleteImg(item: any) {
  dialog.info({
    title: '删除图片',
    content: '请问是否确认删除该图片？',
    positiveText: '确定',
    negativeText: '返回',
    onPositiveClick: async () => {
      const { data, error } = await deleteFileInfo({ idList: item.id });
      if (!error) {
        message.success('已删除');
        emit('refresh', props.thirdParentId, searchParams);
      }
    },
    onNegativeClick: () => {
      message.warning('已取消');
    }
  });
}

const uploadFileType = ref();

onMounted(() => {
  getLabelAllList();
});

// 编辑图片信息
async function handleSubmit() {
  await formRef.value?.validate(async (errors: any) => {
    if (!errors) {
      const checkParams: any = {
        moduleValue: localStg.get('moduleId') || 1,
        keyword: `${nameForm.value.fileCname}`
      };

      const { data: checkData, error: checkError } = await msgCheckAction(checkParams);
      if (!checkError) {
        if (checkData && checkData.length > 0) {
          dialog.error({
            title: '温馨提示',
            content: `图片名称中包含以下敏感词：\n${checkData.join('，')}`,
            style: 'white-space: pre-line;',
            positiveText: '确认'
          });
          return;
        }
      }

      const { data, error } = await updateFolderInfo({
        ...nameForm.value,
        folderId: props.thirdParentId
      });
      if (!error) {
        emit('refresh', props.thirdParentId, searchParams);
        showModal.value = false;
        window.$message?.success('修改信息成功!');
      }
    }
  });
}

const dateFormatted = ref<string[] | null>(null);

const dateExpired = ref<string[] | undefined>(undefined);

// 时间范围确认
function dateConfirm(value: [number, number], formattedValue: [string, string]) {
  const time = formattedValue || ['', ''];
  nameForm.value.startTime = time[0];
  nameForm.value.endTime = time[1];
}

function dateExpiredConfirm(value: [number, number], formattedValue: [string, string]) {
  dateExpired.value = formattedValue;
}
</script>

<template>
  <div class="w-full">
    <div class="tips">
      <!-- 注：1、限制上传文件不同名。2、当同名文件根据后续“1.2.3..."拾取。3、完善自己的知识库 -->
    </div>
    <div style="display: flex">
      <div class="search-box">
        <NInput
          v-model:value="searchParams.fileCname"
          placeholder="请输入图片名称"
          size="large"
          clearable
          @keyup.enter.native="handleSearch"
        >
          <template #suffix>
            <NButton text style="font-size: 24px" @click="handleSearch">
              <NIcon :component="Search" />
            </NButton>
          </template>
        </NInput>
      </div>
      <div class="btn-group">
        <div class="commonBtn" :class="[btnValue == '0' ? 'activeBtn' : '']" @click="handleChangeBtn(0)">全部</div>
        <div
          v-for="imgTab in tabs"
          :key="imgTab.dictValue"
          class="commonBtn"
          :class="[imgTab.dictValue == btnValue ? 'activeBtn' : '']"
          @click="handleChangeBtn(imgTab.dictValue)"
        >
          {{ imgTab.dictLabel }}
        </div>
      </div>
    </div>
    <div class="files">
      <div class="uploadFile file" @click="activate('right')">
        <img class="typeImg" src="@/assets/bid-materials/imgCover.png" alt="" />
        <div class="fileName">
          <NButton color="#FFFFFF" text-color="#333333" strong style="width: 200px; font-size: 16px">上传照片</NButton>
          <div class="notice">· 只支持 jpg png 格式</div>
        </div>
      </div>
      <div v-for="item in $props.fileData" :key="item.id" class="file imageFile">
        <img
          v-if="item.validStatus == 1"
          src="@/assets/bid-materials/expire.png"
          alt=""
          style="width: 50px; position: absolute; right: 0px"
        />
        <NImage width="90%" :src="imgUrl + item.filePath" />
        <div class="imageCname">{{ item.fileCname }}</div>
        <div class="mask">
          <img src="@/assets/bid-materials/mask.png" alt="" style="width: 280px; height: 50px" />
        </div>
        <NButton
          text
          style="font-size: 23px; font-weight: bold; position: absolute; color: antiquewhite; top: 150px; right: 30px"
          @click="handleChangeName(item)"
        >
          <NIcon>
            <CreateOutline />
          </NIcon>
        </NButton>
        <NButton
          text
          style="font-size: 22px; font-weight: bold; position: absolute; color: antiquewhite; top: 151px; right: 5px"
          @click="handleDeleteImg(item)"
        >
          <NIcon>
            <TrashBinOutline />
          </NIcon>
        </NButton>
      </div>
    </div>
  </div>
  <NDrawer v-model:show="active" :width="600" :placement="placement" :mask-closable="false">
    <NDrawerContent title="图片上传" closable>
      <template #header>图片上传</template>
      <NFormItem label="素材类型" path="fileLabel" label-placement="left" size="large" required>
        <NSelect
          v-model:value="uploadFileType"
          clearable
          :options="tabs"
          label-field="dictLabel"
          value-field="dictValue"
        />
      </NFormItem>
      <NFormItem label="素材有效期" label-placement="left" size="large">
        <NDatePicker
          v-model:formatted-value="dateExpired"
          style="width: 100%"
          :default-time="[undefined, '23:59:59']"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          clearable
          separator="至"
          @confirm="dateExpiredConfirm"
        />
      </NFormItem>
      <NSpin :show="dataLoading">
        <NUpload multiple directory-dnd accept=".jpg, .png" :on-after-leave="closeDrawer()" @change="handleChange">
          <NUploadDragger>
            <div style="margin-bottom: 12px; display: flex; justify-content: center">
              <img style="width: 70px; height: 59px" src="@/assets/bid-materials/folder.png" alt="" />
            </div>
            <NText style="font-size: 16px">点击或者拖动文件到该区域来上传</NText>
            <NP depth="3" style="margin: 8px 0 0 0">· 支持扩展名:jpg，png</NP>
          </NUploadDragger>
        </NUpload>
      </NSpin>
      <template #footer>
        <NButton type="primary" style="width: 110px; height: 42px" @click="handleClick">确 定</NButton>
      </template>
    </NDrawerContent>
  </NDrawer>
  <NModal v-model:show="showModal">
    <NCard
      header-style="font-size: 32px;colo: '#333333'"
      footer-style="text-align:center"
      style="width: 700px; border-radius: 30px"
      title="编辑图片"
      :bordered="false"
      size="huge"
      role="dialog"
      aria-modal="true"
      closable
      @close="
        () => {
          showModal = false;
        }
      "
    >
      <NForm
        ref="formRef"
        label-placement="left"
        label-width="100"
        size="large"
        style="margin-top: 30px"
        :model="nameForm"
        :rules="rules"
      >
        <NFormItem label="图片名称" required path="fileCname">
          <NInput v-model:value="nameForm.fileCname" placeholder="请输入" />
        </NFormItem>

        <NFormItem label="素材类型" required path="fileLabel">
          <NSelect
            v-model:value="nameForm.fileLabel"
            clearable
            :options="tabs"
            label-field="dictLabel"
            value-field="dictValue"
          />
        </NFormItem>
        <NFormItem label="素材有效期">
          <NDatePicker
            v-model:formatted-value="dateFormatted"
            style="width: 520px"
            :default-time="[undefined, '23:59:59']"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetimerange"
            clearable
            separator="至"
            @confirm="dateConfirm"
          />
        </NFormItem>
      </NForm>
      <template #footer>
        <NButton secondary type="primary" size="large" @click="handleSubmit">提 交</NButton>
      </template>
    </NCard>
  </NModal>
</template>

<style scoped lang="scss">
.tips {
  margin-left: 20px;
  margin-top: 30px;
  font-weight: 400;
  font-size: 18px;
  color: #4501b7;
}
.search-box {
  line-height: 50px;
  margin-top: 13px;
  margin-left: 32px;
  width: 464px;
}
.btn-group {
  padding-top: 12px;
  margin-left: 80px;
  display: flex;
  justify-content: flex-start;
  .commonBtn {
    cursor: pointer;
    width: 100px;
    height: 48px;
    line-height: 47px;
    font-weight: 400;
    font-size: 17px;
    color: #333333;
    text-align: center;
    border-radius: 6px;
    transition: all 0.2s ease;
  }
  .activeBtn {
    color: #806cfe;
    background: #f2f0ff;
    opacity: 0.9;
  }
}
.files {
  padding-top: 20px;
  width: 1583px;
  height: 610px;
  display: flex;
  flex-wrap: wrap;
  :deep(.n-image) {
    display: flex;
    justify-content: center;
  }
  .file {
    width: 281px;
    height: 180px;
    border-radius: 12px;
    border: 1px solid #ebeef5;
    margin: 16px 16px;
    position: relative;
    &:hover {
      background: #f3f4f8;
      cursor: pointer;
    }
  }
}
.uploadFile {
  background: #f3f4f8;
  .typeImg {
    position: absolute;
    top: 30px;
    left: 106px;
    width: 70px;
    height: 59px;
  }
  .fileName {
    text-align: center;
    width: 281px;
    padding: 0 30px;
    margin-top: 100px;
    font-weight: 400;
    font-size: 18px;
    color: #333333;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    line-clamp: 1; /* 这里的3表示最多显示2行 */
    overflow: hidden;
  }
  .notice {
    margin-top: 8px;
    font-weight: 900;
    font-size: 15px;
    color: #cccccc;
  }
}
.imageFile {
  display: flex;
  justify-content: center;
  position: relative;
  .imageCname {
    display: inline;
    position: absolute;
    overflow: hidden;
    width: 180px;
    bottom: 8px;
    line-height: 18px;
    left: 10px;
    font-weight: 400;
    font-size: 15px;
    color: #ffffff;
    z-index: 999;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .mask {
    position: absolute;
    bottom: 0px;
    left: 0px;
  }
}
</style>
